import { PauseCircleOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { Slider } from 'antd';
import React, { Component } from 'react';
import { formatSecond } from 'utils/tools';

type IProps = {
  /**播放器唯一标识 */
  id: string;
  /**播放地址 */
  src: string;
  /**父组件已存在的播放器
   * 例如：chat组件中，父组件包含单句播放，交互时需考虑切音效果
   */
  outAudio?: any;
  /** 播放事件*/
  onAudioPlay?: any;
  /** 暂停事件*/
  onAudioPause?: any;
};

type IState = {
  rateList: Array<number>;
  playRate: number;
  isPlay: boolean;
  isMuted: boolean;
  volume: number;
  allTime: number;
  currentTime: number;
};

/**
 * 录音播放组件
 */
export class WAudio extends Component<IProps, IState> {
  audio: HTMLAudioElement;
  audioDom: any;
  constructor(props: IProps) {
    super(props);

    this.audio = undefined as any;
    this.audioDom = undefined;
    this.state = {
      rateList: [1.0, 1.25, 1.5, 2.0],
      playRate: 1.0,
      isPlay: false,
      isMuted: false,
      volume: 100,
      allTime: 0,
      currentTime: 0,
    };
  }

  componentDidMount() {
    console.log('wAudio======DidMount');
  }

  // 该视频已准备好开始播放
  onCanPlay = () => {
    const { outAudio, id } = this.props;
    this.audio = document.getElementById(`audio${id}`) as HTMLAudioElement;
    console.log('wAudio======ready,can play', this.audio.duration);
    // 外部单句播放暂停
    outAudio && outAudio.pause();
    this.audio &&
      this.setState({
        allTime: this.audio.duration,
      });
  };
  /**播放 */
  playAudio = () => {
    this.audio?.play();
    console.log(this.props.id, '播放', this.state.allTime);
    this.setState(
      {
        isPlay: true,
      },
      () => {
        this.props.onAudioPlay && this.props.onAudioPlay();
      }
    );
  };

  /**暂停 */
  pauseAudio = () => {
    this.audio?.pause();
    console.log(this.props.id, '暂停');
    this.setState(
      {
        isPlay: false,
      },
      () => {
        this.props.onAudioPause && this.props.onAudioPause();
      }
    );
  };

  /**调进度 */
  changeTime = (value: number) => {
    console.log('进度调整：', value);
    this.setState(
      {
        currentTime: value,
      },
      () => {
        this.audio.currentTime = value;
        if (value === this.state.allTime) {
          // 录音播放结束
          this.setState({
            isPlay: false,
          });
        }
      }
    );
  };

  // 当前播放位置改变时执行
  onTimeUpdate = () => {
    this.setState({
      currentTime: this.audio.currentTime,
    });
    if (this.audio.currentTime === this.state.allTime) {
      // 录音播放结束
      this.setState({
        isPlay: false,
      });
    }
  };

  /**静音 */
  onMuteAudio = () => {
    this.setState({
      isMuted: !this.audio.muted,
    });
    this.audio.muted = !this.audio.muted;
  };

  /**调音量 */
  changeVolume = (e: any) => {
    const { value } = e.target;
    this.audio.volume = value / 100;

    this.setState({
      volume: value,
      isMuted: !value,
    });
  };

  /** 倍速播放*/
  changePlayRate = (num: any) => {
    this.audioDom.playbackRate = num;
    this.setState({
      playRate: num,
    });
  };

  render() {
    const { src, id } = this.props;

    const {
      isPlay,
      allTime,
      currentTime,
      // isMuted, volume, rateList, playRate
    } = this.state;

    return (
      <div className="w-audio">
        <audio
          id={`audio${id}`}
          src={src}
          ref={audio => {
            this.audioDom = audio;
          }}
          preload={'auto'}
          onCanPlay={this.onCanPlay}
          onTimeUpdate={this.onTimeUpdate}
        >
          <track src={src} kind="captions" />
        </audio>
        <div className="btn-operation">
          {isPlay ? (
            <PauseCircleOutlined className="btn-icon btn-pause" onClick={this.pauseAudio} />
          ) : (
            <PlayCircleOutlined className="btn-icon btn-play" onClick={this.playAudio} />
          )}
        </div>
        <Slider
          className="time-line"
          step={1}
          min={0}
          max={Math.ceil(allTime)}
          value={Math.ceil(currentTime)}
          tipFormatter={null}
          onChange={this.changeTime}
        />
        <span className="time-detail">
          {formatSecond(currentTime) + '/' + formatSecond(allTime)}
        </span>
        {/* ****以下功能需求中暂无 */}
        {/* <div onClick={this.onMuteAudio}>静音</div> */}

        {/* <div>
          <span>音量调节：</span>
          <input type="range" onChange={this.changeVolume} value={isMuted ? 0 : volume} />
        </div> */}

        {/* <div>
          <span>倍速播放：</span>
          {rateList &&
            rateList.length > 0 &&
            rateList.map(item => (
              <button
                key={item}
                style={
                  playRate === item
                    ? {
                        border: '1px solid #188eff',
                        color: '#188eff',
                      }
                    : undefined
                }
                onClick={() => this.changePlayRate(item)}
              >
                {item}
              </button>
            ))}
        </div> */}
      </div>
    );
  }
}
